package com.sto.stoapp.http;

import static com.sto.stoapp.http.ServerSmsHttpManager.CONNECT_TIME_OUT;
import static com.sto.stoapp.http.ServerSmsHttpManager.FORMAT;
import static com.sto.stoapp.http.ServerSmsHttpManager.READ_TIME_OUT;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.sto.stoapp.entity.JsonEntity;

/**
 * Json下载上传数据处理
 * 
 * @author hb
 * 
 */
public class JsonUploadHttpManager {

	/** 上传数据 **/
	public String postData(JsonEntity jsonEntity) {
		String result = "";
		HttpPost hp = new HttpPost(jsonEntity.getURL());
		hp.setHeader("Connection", "close");
		HttpClient client = setTimeOutClient();
		try {

			ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			pairs.add(new BasicNameValuePair(jsonEntity.getDataName(),
					jsonEntity.getData()));
			pairs.add(new BasicNameValuePair(jsonEntity.getKeyName(),
					jsonEntity.getKey()));
			Log.e("发送数据 = ", pairs.toString());
			
			hp.setEntity(new UrlEncodedFormEntity(pairs, FORMAT));
			
			HttpResponse response = client.execute(hp);
			if (response.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(response.getEntity(), FORMAT);
			}

		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			jsonEntity = null;
			client.getConnectionManager().shutdown();
		}

		return result;
	}

	/**
	 * 设置超时时间和创建httpClient
	 * 
	 * @return
	 */
	private HttpClient setTimeOutClient() {
		HttpParams params = new BasicHttpParams(); // 实例化Post参数对象
		HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIME_OUT);// 设置请求超时
		HttpConnectionParams.setSoTimeout(params, READ_TIME_OUT); // 设置响应超时
		HttpClient client = new DefaultHttpClient(params); // 实例化一个连接对象
		return client;
	}

}
